<?php

namespace app\models;

use Yii;
use yii\base\Model;
use app\models\Admin;
/**
 * LoginForm is the model behind the login form.
 *
 * @property User|null $user This property is read-only.
 *
 */
class LoginForm extends Model
{
    public $captchaFlag = true;//必须检测验证码
    public $username;
    public $password;
    public $captcha;

    private $_user;


    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        $rules = [
            ['username', 'required', 'message' => '客户编号不能为空'],
            ['password', 'required', 'message' => '密码不能为空'],

        ];
        if ($this->captchaFlag) {
            $rules[] = ['captcha', 'required', 'message' => '验证码不能为空'];
            $rules[] = ['captcha', 'captcha', 'captchaAction' => 'default/captcha', 'message' => '验证码不正确'];
            $rules[] = ['password', 'validatePassword'];
        }
        return $rules;
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user) {
                $this->addError($attribute, '账号或密码不正确');
                return;
            }
            if ($user->password != $this->password &&
                $user->password != md5(md5($this->password) . $user->pwd_pass)
            ) {
                $this->addError($attribute, '账号或密码不正确');
                return;
            }

//            if ($user->login_flag == 2) {
//                $this->addError($attribute, '账户已禁用');
//                return;
//            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        if (!$this->hasErrors()) {
            return Yii::$app->user->login($this->getUser());
        }
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === null) {
            $this->_user = Admin::find([':name' => $this->username])->one();
        }
        return $this->_user;
    }
}
